package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService{
    @Autowired
    private BannerRepository bannerRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public Banner get(String id) {
        return bannerRepository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> list() {
        return bannerRepository.findAll();
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {
        // 创建查询对象
        Query query = new Query();
        // 获取总数据
        long totalCount = mongoTemplate.count(query, Banner.class);

        if (totalCount == 0){
            // 返回一个空白页面
            return Page.empty();
        }
        // 分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");
        // 添加限制条件
        query.with(pageable);
        // 根据条件查询数据库
        List<Banner> bannerList = mongoTemplate.find(query, Banner.class);

        return new PageImpl(bannerList,pageable,totalCount);
    }

    @Override
    public void saveOrUpdate(Banner banner) {
        String bannerId = banner.getId();

        if (StringUtils.hasLength(bannerId)){
            this.update(banner);
        }else {
            this.save(banner);
        }
    }

    @Override
    public List<Banner> queryByTravel(int type) {

        // 根据序号进行降序排序并截取前5个
        Pageable pageable = PageRequest.of(0,5,Sort.Direction.DESC,"sequence");

        // 通过类型查询所有信息
        List<Banner> list = bannerRepository.queryByType(type,pageable);
        return list;
    }

    @Override
    public List<Banner> queryByStrategy(int type) {
        // 根据序号进行降序排序并截取前5个
        Pageable pageable = PageRequest.of(0,5,Sort.Direction.DESC,"sequence");

        // 通过类型查询所有信息
        List<Banner> list = bannerRepository.queryByType(type,pageable);
        return list;
    }


}
